#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p)
    {
        if (p->right != nullptr)
        {
            TreeNode* next = GetLeft(p->right);
            return next;
        }
        else
        {
            std::vector<TreeNode*> path;
            GetPath(root, p, path);

            TreeNode* cur = path.back();
            path.pop_back();

            while (!path.empty())
            {
                TreeNode* parent = path.back();
                path.pop_back();

                if (parent->left == cur)
                {
                    return parent;
                }

                cur = parent;
            }

            return nullptr;
        }
    }

private:
    TreeNode* GetLeft(TreeNode* root)
    {
        TreeNode* cur = root;
        while (cur->left)
        {
            cur = cur->left;
        }
        return cur;
    }

    void GetPath(TreeNode* root, TreeNode* p, std::vector<TreeNode*>& path)
    {
        TreeNode* cur = root;
        while (cur != p)
        {
            path.push_back(cur);

            if (cur->val > p->val) {
                cur = cur->left;
            }
            else {
                cur = cur->right;
            }
        }
        path.push_back(cur);
    }
};